//Copyright (c) 2017. 章钦豪. All rights reserved.
package com.wandousoushu.jiusen

import android.Manifest
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.webkit.WebView
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.wandousoushu.jiusen.bean.AdBean
import com.wandousoushu.jiusen.bean.H5AdBean
import com.wandousoushu.jiusen.bean.PayRule
import com.wandousoushu.jiusen.bean.UserInfo
import com.wandousoushu.jiusen.booksource.bean.BookChapter
import com.wandousoushu.jiusen.booksource.bean.Cookie
import com.wandousoushu.jiusen.booksource.constant.EventBus
import com.wandousoushu.jiusen.booksource.constant.PreferKey
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.data.entities.BookSource
import com.wandousoushu.jiusen.booksource.data.entities.SearchBook
import com.wandousoushu.jiusen.booksource.model.BookChapterManager
import com.wandousoushu.jiusen.booksource.model.BookManager
import com.wandousoushu.jiusen.booksource.model.SearchBookManager
import com.wandousoushu.jiusen.help.ActivityHelp
import com.wandousoushu.jiusen.help.AppConfig
import com.wandousoushu.jiusen.help.CrashHandler
import com.wandousoushu.jiusen.help.ReadBookConfig
import com.wandousoushu.jiusen.lib.theme.ThemeStore
import com.wandousoushu.jiusen.util.*
import com.wandousoushu.jiusen.web.http.MainHttpUtils
import java.util.*

class MyApplication : Application() {
    var token: String? = null
    var phoneNum: String? = null
    var nickName: String? = null
    var userId = 0
    var isVip = false
    lateinit var userinfo: UserInfo
    var isLogin=true
    var isWxUser=false;
    var wxLoginState="wandousoushuwxstate"


    private val cookieList = HashMap<String, Cookie>()
    private val mPayRules: MutableList<PayRule> = ArrayList()//支付规则

//    var pageAdList: MutableList<AdBean> = ArrayList()
//    var pageAdBean: AdBean?=null
//    var pageAdIndex=0

    var pageH5:H5AdBean?=null

    override fun onCreate() {
        super.onCreate()
        instance = this
        CrashHandler().init(this)

        //友盟统计
        UMConfigure.init(this, "5f6840a1b473963242a2fb70", "com.wandousoushu.jiusen", UMConfigure.DEVICE_TYPE_PHONE, "");
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);

        applyDayNight()
        LiveEventBus
                .config()
                .supportBroadcast(this)
                .lifecycleObserverAlwaysActive(true)
                .autoClear(false)

        //registerActivityLifecycleCallbacks(ActivityHelp)
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
    }


    fun AddCookie(cookie: Cookie) {
        cookieList[cookie.url] = cookie
    }

    fun GetCookie(url: String?): Cookie? {
        return cookieList[url]
    }

    fun RemoveCookie(url: String?) {
        cookieList.remove(url)
    }

    fun GetCookieList(): List<Cookie> {
        return cookieList.values as List<Cookie>
    }

    fun ClearCookie() {
        cookieList.clear()
    }

    fun AddPayRules(payRule: List<PayRule>) {
        mPayRules.clear();
        mPayRules.addAll(payRule)
    }

    fun getPayRuleList(): List<PayRule> {
        return mPayRules
    }

    fun setWxUser(openid:String){
        isWxUser=true
        putPrefBoolean("isWxUser", true)
        putPrefString("openid", openid)
    }

    companion object {
        @JvmStatic
        lateinit var instance: MyApplication
            private set

        val versionName: String? = null
        const val versionCode = 0
        const val MaxThreadCount = 15

        val appResources: Resources
            get() = instance.resources

    }

    fun applyTheme() {
        when {
            AppConfig.isEInkMode -> {
                ThemeStore.editTheme(this)
                        .coloredNavigationBar(true)
                        .primaryColor(Color.WHITE)
                        .accentColor(Color.BLACK)
                        .backgroundColor(Color.WHITE)
                        .bottomBackground(Color.WHITE)
                        .apply()
            }
            AppConfig.isNightTheme -> {
                val primary =
                        getPrefInt(PreferKey.cNPrimary, getCompatColor(R.color.md_blue_grey_600))
                val accent =
                        getPrefInt(PreferKey.cNAccent, getCompatColor(R.color.colorPrimary))
                var background =
                        getPrefInt(PreferKey.cNBackground, getCompatColor(R.color.md_grey_900))
                if (ColorUtils.isColorLight(background)) {
                    background = getCompatColor(R.color.md_grey_900)
                    putPrefInt(PreferKey.cNBackground, background)
                }
                val bBackground =
                        getPrefInt(PreferKey.cNBBackground, getCompatColor(R.color.md_grey_850))
                ThemeStore.editTheme(this)
                        .coloredNavigationBar(true)
                        .primaryColor(ColorUtils.withAlpha(primary, 1f))
                        .accentColor(ColorUtils.withAlpha(accent, 1f))
                        .backgroundColor(ColorUtils.withAlpha(background, 1f))
                        .bottomBackground(ColorUtils.withAlpha(bBackground, 1f))
                        .apply()
            }
            else -> {
                val primary =
                        getPrefInt(PreferKey.cPrimary, getCompatColor(R.color.colorPrimary))
                val accent =
                        getPrefInt(PreferKey.cAccent, getCompatColor(R.color.colorPrimaryDark))
                var background =
                        getPrefInt(PreferKey.cBackground, getCompatColor(R.color.md_grey_100))
                if (!ColorUtils.isColorLight(background)) {
                    background = getCompatColor(R.color.md_grey_100)
                    putPrefInt(PreferKey.cBackground, background)
                }
                val bBackground =
                        getPrefInt(PreferKey.cBBackground, getCompatColor(R.color.md_grey_200))
                ThemeStore.editTheme(this)
                        .coloredNavigationBar(true)
                        .primaryColor(ColorUtils.withAlpha(primary, 1f))
                        .accentColor(ColorUtils.withAlpha(accent, 1f))
                        .backgroundColor(ColorUtils.withAlpha(background, 1f))
                        .bottomBackground(ColorUtils.withAlpha(bBackground, 1f))
                        .apply()
            }
        }
    }

    fun applyDayNight() {
        ReadBookConfig.upBg()
        applyTheme()
        initNightMode()
        postEvent(EventBus.RECREATE, "")
    }

    private fun initNightMode() {
        val targetMode =
                if (AppConfig.isNightTheme) {
                    AppCompatDelegate.MODE_NIGHT_YES
                } else {
                    AppCompatDelegate.MODE_NIGHT_NO
                }
        AppCompatDelegate.setDefaultNightMode(targetMode)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
            Configuration.UI_MODE_NIGHT_YES, Configuration.UI_MODE_NIGHT_NO -> applyDayNight()
        }
    }



    fun Clear() {
        BookManager.GetInstance().clear()
        SearchBookManager.GetInstance().clear()
        BookChapterManager.GetInstance().clear()
        mPayRules.clear()
        ClearCookie()
        isLogin=false
        isWxUser=false
        //pageAdList.clear()
        wxLoginState="wandousoushuwxstate"
    }

}